using System;
using System.IO;
using System.Net;

namespace Framework.Library.Core.Utils.IO
{
    public class WebRequestStreamGetter : IStreamGetter
    {
        private string _proxyDomain;
        private string _proxyPassword;
        private string _proxyUserName;
        private Uri _requestUri;
        private string _userAgent;

        public string ProxyUserName
        {
            get { return _proxyUserName; }
            set { _proxyUserName = value; }
        }

        public string ProxyPassword
        {
            get { return _proxyPassword; }
            set { _proxyPassword = value; }
        }

        public string ProxyDomain
        {
            get { return _proxyDomain; }
            set { _proxyDomain = value; }
        }

        public Uri RequestUri
        {
            get { return _requestUri; }
            set { _requestUri = value; }
        }

        public string UserAgent
        {
            get { return _userAgent; }
            set { _userAgent = value; }
        }

        #region IStreamGetter Members

        public Stream GetStream()
        {
            if (_requestUri == null)
                throw new InvalidOperationException("RequestUri must be set.");

            WebRequest webRequest = WebRequest.Create(_requestUri);
            webRequest.Method = "GET";
            webRequest.Timeout = 60000;
            if (!string.IsNullOrEmpty(_proxyUserName))
            {
                if (webRequest.Proxy == null)
                    throw new InvalidOperationException("No proxy on WebRequest. Could not set proxy credentials.");

                webRequest.Proxy.Credentials = new NetworkCredential(_proxyUserName, _proxyPassword, _proxyDomain);
            }

            if (webRequest is HttpWebRequest)
                ((HttpWebRequest) webRequest).UserAgent = _userAgent;

            WebResponse webResponse = webRequest.GetResponse();

            return webResponse.GetResponseStream();
        }

        #endregion
    }
}